package cn.wolfcode.luowowo.controller;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("users")
public class UserController {

    //解决短信硬编码
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.sign}")
    private String smsSign;
    @Value("${sms.appkey}")
    private String smsAppkey;




    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    /**
     * 查询单个用户
     * @param id
     * @return
     */
    @GetMapping("/get")
    public Object get(String id){
        return userInfoService.get(id);
    }

    //判断用户是否已注册
    @GetMapping("/checkPhone")
    public boolean checkPhone(String phone){
        boolean ret = userInfoService.checkPhone(phone);
        return ret;
    }

    //获取短信验证码操作
    @GetMapping("/sendVerifyCode")
    public JsonResult sendVerifyCode(String phone){
        //调用短信业务方法
        userInfoService.sendVerifyCode(phone,smsAppkey,smsUrl,smsSign);
        return JsonResult.success();
    }


    //用户完成注册
    @PostMapping("/regist")
    public JsonResult regist(String phone,String nickname,String password,String rpassword,String verifyCode ) {
        userInfoService.regist(phone, nickname, password, rpassword, verifyCode);
        return JsonResult.success();

    }

    //用户登入
    @PostMapping("/login")
    public Object login(String username,String password){
        //判断用户名密码
        UserInfo userInfo = userInfoService.checkLogin(username, password);
        //将用户设置时效存入redis中
        String token = userInfoRedisService.setToken(userInfo);
        //map形式返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);//前端设置请求头
        map.put("userInfo",userInfo);//前端显示用户
        return JsonResult.success(map);
    }

    //模拟当前登入用户
    @RequireLogin
    @GetMapping("/getCurrentUser")
    public Object getCurrentUsert(HttpServletRequest request){
        String token = request.getHeader("token");
        UserInfo userInfo = userInfoRedisService.getToken(token);
        return JsonResult.success(userInfo);
    }

}
